//
//  NSTreeExt.m
//  WebClipper
//
//  Created by Daniel Braun on 24/02/07.
//  Copyright 2007Daniel Braun http://page-appart.net, http://braun.daniel.free.fr  All rights reserved.
//

#import "NSTreeExt.h"


@implementation NSTreeController (Ext)
//http://wilshipley.com/blog/2006/04/pimp-my-code-part-10-whining-about.html
- (NSIndexPath *)_indexPathFromIndexPath:(NSIndexPath *)baseIndexPath inChildren:(NSArray *)children
			      childCount:(unsigned int)childCount toObject:(id)object;
{
	unsigned int childIndex;
	for (childIndex = 0; childIndex < childCount; childIndex++) {
		id childObject = [children objectAtIndex:childIndex];
		
		NSArray *childsChildren = nil;
		unsigned int childsChildrenCount = 0;
		NSString *leafKeyPath = [self leafKeyPath];
		if (!leafKeyPath || [[childObject valueForKey:leafKeyPath] boolValue] == NO) {
			NSString *countKeyPath = [self countKeyPath];
			if (countKeyPath)
				childsChildrenCount = [[childObject valueForKey:leafKeyPath] unsignedIntValue];
			if (!countKeyPath || childsChildrenCount != 0) {
				NSString *childrenKeyPath = [self childrenKeyPath];
				childsChildren = [childObject valueForKey:childrenKeyPath];
				if (!countKeyPath)
					childsChildrenCount = [childsChildren count];
			}
		}
		
		BOOL objectFound = [object isEqual:childObject];
		if (!objectFound && childsChildrenCount == 0)
			continue;
		
		NSIndexPath *indexPath = (baseIndexPath == nil) ? [NSIndexPath indexPathWithIndex:childIndex]
								: [baseIndexPath indexPathByAddingIndex:childIndex];
		
		if (objectFound)
			return indexPath;
		
		NSIndexPath *childIndexPath = [self _indexPathFromIndexPath:indexPath inChildren:childsChildren
								 childCount:childsChildrenCount toObject:object];
		if (childIndexPath)
			return childIndexPath;
	}
	
	return nil;
}
- (NSIndexPath *)indexPathToObject:(id)object;
{
	NSArray *children = [self content];
	return [self _indexPathFromIndexPath:nil inChildren:children childCount:[children count]
				    toObject:object];
}

@end
